// #ifdef APP-PLUS
import {findDB, deleteDB} from './db.js'
import {uploadRecordMore, uploadRecordRegular} from '../api.js'
// 定时任务
export const task = {
	times: 1000 * 60 * 5,
	task1: function (data) {
		// 安装使用
		uploadRecordMore(data.map(d => {
			return {
				devicesUseStatus: d.devicesUseStatus,
				recordType: d.recordType,
				reportContent: d.reportContent,
				devicesGeolocation: d.devicesGeolocation,
				devicesGeolocationName: d.devicesGeolocationName,
				traceCode: d.traceCode
			}
		}), false).then(res => {
			console.log('定时任务1:uploadRecordMore', res)
			if (res.code === 20000 || (res.code === 30000 && (!res.msg || res.msg.indexOf('request:fail abort statusCode:-1') !== 0))) {
				data.forEach(d => {
					deleteDB(d.id).then(res => {
						console.log('删除缓存数据id:', d.id, res)
					})
				})
				uni.$emit('refresh-history')
				uni.$emit('refresh-device')
			}
		})
	},
	task2: function (data) {
		// 定期上报
		uploadRecordRegular({
			devicesGeolocation: data[0].devicesGeolocation,
			devicesGeolocationName: data[0].devicesGeolocationName,
			content: '设备定期上报',
			codes: data.map(d => d.traceCode).join(';')
		}, {cache: false}).then(res => {
			console.log('定时任务2:uploadRecordRegular', res)
			if (res.code === 20000 || (res.code === 30000 && (!res.msg || res.msg.indexOf('request:fail abort statusCode:-1') !== 0))) {
			
				data.forEach(d => {
					deleteDB(d.id).then(res => {
						console.log('删除缓存数据id:', d.id, res)
					})
				})
				uni.$emit('refresh-history')
				uni.$emit('refresh-device')
			}
		})
	},
	run: function() {
		// 执行任务
		console.log('正在执行定时任务。。。。。', task.times)
		findDB().then(db => {
			console.log('正在执行定时任务。。。。。查询缓存数：', db.length)
			let task1data = db.filter(d => d.recordType === '安装使用')
			let task2data = db.filter(d => d.recordType === '定期上报')
			if (task1data && task1data.length > 0) {
				task.task1(task1data)
			}
			if (task2data && task2data.length > 0) {
				task.task2(task2data)
			}
		})
		setTimeout(task.run, task.times)
	}
}
console.log('times====', task.times)
// 5s后执行
setTimeout(task.run, 0)
// #endif
